﻿using Sidvall.Serialization;
using System.Collections.Generic;

namespace Sidvall.Security
{
	public static class AuthenticationContext
	{
		public const string KeyValueSeparator = ":";
		public const string ItemSeparator = "|";

		public static string FindValue(IEnumerable<string> values, string key)
		{
			if (values == null)
				return null;
			foreach (var value in values)
			{
				var parts = value.Split(KeyValueSeparator, System.StringSplitOptions.RemoveEmptyEntries);
				if (parts.Length > 1)
				{
					if (parts[0].Equals(key, true, System.StringComparison.OrdinalIgnoreCase))
						return parts[1];
				}
			}
			return null;
		}

		public static string GetAuthenticationContextReferences(TwoFactorProvider provider)
		{
			switch (provider)
			{
				case TwoFactorProvider.Email:
				case TwoFactorProvider.Sms:
					return AuthenticationMethods.TwoFactorAuthentication + KeyValueSeparator + provider.ToString();
				default:
					return null;
			}
		}

		public static TwoFactorProvider GetTwoFactorProvider(string authenticationContextReferences)
		{
			if (string.IsNullOrWhiteSpace(authenticationContextReferences))
				return TwoFactorProvider.None;
			var items = authenticationContextReferences.Split(ItemSeparator, System.StringSplitOptions.RemoveEmptyEntries);
			return GetTwoFactorProvider(items);
		}

		public static TwoFactorProvider GetTwoFactorProvider(IEnumerable<string> authenticationContextReferences)
		{
			var twoFactorProvider = FindValue(authenticationContextReferences, AuthenticationMethods.TwoFactorAuthentication);
			return twoFactorProvider.ToEnum<TwoFactorProvider>(TwoFactorProvider.None);
		}
	}
}
